package utils

import (
	"errors"
	"regexp"
)

// Types 类型集合
type Types interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 |
		~uint16 | ~uint32 | ~uint64 | ~uintptr | ~float32 | ~float64 | ~string
}

func In[T Types](target T, arr []T) (bool, int) {
	for idx, item := range arr {
		if target == item {
			return true, idx
		}
	}
	return false, 0
}

// Contain 包含
func Contain[T Types](target T, arr []T) bool {
	for _, item := range arr {
		if target == item {
			return true
		}
	}
	return false
}

func NullOrError(err error, msg string) error {
	if err != nil {
		return err
	}
	return errors.New(msg)
}

type ITree[T ~int64 | ~uint64 | string, V any] interface {
	Key() T
	Parent() T
	SetChildren(children []V)
}

func BuildTree[E ~int64 | ~uint64 | string, V ITree[E, V]](pId E, data []V) []V {
	if data == nil || len(data) == 0 {
		return nil
	}
	result := make([]V, 0)
	residue := make([]V, 0)
	for _, item := range data {
		if item.Parent() == pId {
			result = append(result, item)
		} else {
			residue = append(residue, item)
		}
	}

	if len(result) != 0 {
		for _, item := range result {
			item.SetChildren(BuildTree[E, V](item.Key(), residue))
		}
	}

	return result

}

// IsHexColor 是否为16进制颜色字符串
func IsHexColor(color string) bool {
	matched, _ := regexp.MatchString(`^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{8})$`, color)
	return matched
}
